<template>
  <canvas id="particles"></canvas>
</template>

<script>
import { onMounted, onUnmounted } from 'vue'

export default {
  name: 'ParticleBackground',
  setup() {
    let canvas
    let ctx
    let particles = []
    const particleCount = 150
    const connectDistance = 120
    let animationFrameId

    class Particle {
      constructor() {
        this.x = Math.random() * canvas.width
        this.y = Math.random() * canvas.height
        this.size = Math.random() * 3 + 1
        this.speedX = Math.random() * 1 - 0.5
        this.speedY = Math.random() * 1 - 0.5
      }

      update() {
        this.x += this.speedX
        this.y += this.speedY

        if (this.x > canvas.width - this.size || this.x < this.size) this.speedX *= -1
        if (this.y > canvas.height - this.size || this.y < this.size) this.speedY *= -1
      }

      draw() {
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
        ctx.fill()
      }
    }

    const init = () => {
      for (let i = 0; i < particleCount; i++) {
        particles.push(new Particle())
      }
    }

    const animate = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      for (let i = 0; i < particles.length; i++) {
        particles[i].update()
        particles[i].draw()

        for (let j = i; j < particles.length; j++) {
          const distance = Math.sqrt(
            (particles[i].x - particles[j].x) ** 2 + (particles[i].y - particles[j].y) ** 2,
          )

          if (distance < connectDistance) {
            ctx.beginPath()
            ctx.strokeStyle = `rgba(255, 255, 255, ${1 - distance / connectDistance})`
            ctx.lineWidth = 1
            ctx.moveTo(particles[i].x, particles[i].y)
            ctx.lineTo(particles[j].x, particles[j].y)
            ctx.stroke()
          }
        }
      }

      animationFrameId = requestAnimationFrame(animate)
    }

    const handleResize = () => {
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
      particles = []
      init()
    }

    onMounted(() => {
      canvas = document.getElementById('particles')
      ctx = canvas.getContext('2d')

      canvas.width = window.innerWidth
      canvas.height = window.innerHeight

      init()
      animate()

      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      cancelAnimationFrame(animationFrameId)
    })

    return {}
  },
}
</script>

<style scoped>
#particles {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -2; /* 确保它在内容和主导航栏后面 */
  background-color: transparent; /* 背景透明，让渐变背景显示 */
}
</style>
